package com.huawei.spare.part.replace.views.widgets;

import com.huawei.spare.part.replace.OperationException;
import com.huawei.spare.part.replace.framework.SmartDataBus;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Priority;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Optional;

public class Alerts {

    public static String i18n(String key) {
        if (key != null) {
            return SmartDataBus.getString(key);
        }
        return null;
    }

    public static Optional<ButtonType> confirm(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setHeaderText(i18n(title));
        alert.setContentText(i18n(content));
        return alert.showAndWait();
    }

    public static void info(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setHeaderText(i18n(title));
        alert.setContentText(i18n(content));
        alert.showAndWait();
    }

    public static void error(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setHeaderText(i18n(title));
        alert.setContentText(i18n(content));
        alert.showAndWait();
    }

    public static void operationFailed(OperationException ex) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setHeaderText(i18n(ex.getMajor()));
        alert.setContentText(i18n(ex.getDetails()));
        alert.showAndWait();
    }

    public static void error(Throwable ex) {
        if (ex instanceof OperationException) {
            operationFailed((OperationException) ex);
        } else {
            error(ex, ex.getCause().getLocalizedMessage(), null);
        }
    }

    public static void error(Throwable ex, String title, String content) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setHeaderText(i18n(title));
        alert.setContentText(i18n(content));

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        ex.printStackTrace(pw);
        String exceptionText = sw.toString();

        Label label = new Label(i18n("common.p.title.exception"));

        TextArea textArea = new TextArea(exceptionText);
        textArea.setEditable(false);
        textArea.setWrapText(true);

        textArea.setMaxWidth(Double.MAX_VALUE);
        textArea.setMaxHeight(Double.MAX_VALUE);
        GridPane.setVgrow(textArea, Priority.ALWAYS);
        GridPane.setHgrow(textArea, Priority.ALWAYS);

        GridPane expContent = new GridPane();
        expContent.setMaxWidth(Double.MAX_VALUE);
        expContent.add(label, 0, 0);
        expContent.add(textArea, 0, 1);

        alert.getDialogPane().setExpandableContent(expContent);
        alert.showAndWait();
    }

}
